﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Script.Services;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;
using NetDon.OA.Interface;
using NetDon.OA.Portal.Constants;
using NetDon.Utilities;
using NetDon.WebControls;
using NineRays.WebControls;


namespace NetDon.OA.Portal.Admin
{
    [Function("Admin.DataDictionary")]
    [Navigation("系统管理","数据字典")]
    public partial class DataDictionary : PageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                ShowTypes();
            }
        }

        private void ShowEnties()
        {
            BindEntries();
            if (treeTypes.SelectedNode != null)
            {
                btnAddItem.Enabled = true;
                btnAddItem.OnClientClick = string.Format("btnAddEntryClick('{0}');return false;",
                                                         treeTypes.SelectedNode.Value);
            }
            else
            {
                btnAddItem.Enabled = false;
            }
            foreach (var node in treeTypes.Nodes)
            {
                node.ImageUrl = node.Selected ? ApplicationImages.TreeNodeOpened : ApplicationImages.TreeNodeClosed;
            }
        }

        private void ShowTypes()
        {
            string selectedValue = treeTypes.SelectedNode != null ? treeTypes.SelectedNode.Value : null;
            treeTypes.Nodes.Clear();
            var treeNodes = new List<FlyTreeNode>();
            var service = ServiceContainer.GetService<IDictionaryManageService>();
            foreach (var type in service.GetCategories())
            {
                treeNodes.Add(new FlyTreeNode(type.CategoryName, type.CategoryId.ToString()));
            }
            treeNodes.Sort(
                (x, y) =>
                x.NodeTypeID == y.NodeTypeID
                    ? string.Compare(x.Text, y.Text)
                    : string.Compare(x.NodeTypeID, y.NodeTypeID));
            treeTypes.Nodes.AddRange(treeNodes);
            if (!string.IsNullOrEmpty(selectedValue))
            {
                var node = treeTypes.FindByValue(selectedValue);
                if (node != null)
                {
                    treeTypes.SelectedNode = node;
                }
            }
            if (treeTypes.SelectedNode == null && treeTypes.Nodes.Count > 0)
            {
                treeTypes.SelectedNode = treeTypes.Nodes[0];
            }
            ShowEnties();
        }

        protected void gridItem_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                string value = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "Value"));
                string name = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "Name"));
                var btnMoveUp = e.Row.FindControl("btnMoveUp") as ImageButton;
                if (btnMoveUp != null && e.Row.RowIndex == 0)
                {
                    btnMoveUp.Style["visibility"] = "hidden";
                }
                var btnMoveDown = e.Row.FindControl("btnMoveDown") as ImageButton;
                var service = ServiceContainer.GetService<IDictionaryService>();
                if (btnMoveDown != null && e.Row.RowIndex == service.GetDataItems(treeTypes.SelectedNode.Value.ToGuid()).Count() - 1)
                {
                    btnMoveDown.Style["visibility"] = "hidden";
                }
                var btnDelete = e.Row.FindControl("btnDelete") as ImageButton;
                if (btnDelete != null)
                {
                   btnDelete.OnClientClick = string.Format("btnDeleteEntryClick('{0}');return false;", value);
                }
                var btnModify = e.Row.FindControl("btnModify") as ImageButton;
                if (btnModify != null)
                {
                    btnModify.OnClientClick = string.Format("btnModifyEntryClick('{0}','{1}','{2}');return false;", treeTypes.SelectedNode.Value, value, name.QuoteJavascript());
                }
                e.Row.Attributes["Value"] = value;
            }
        }

        protected void gridItem_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            var row = (GridViewRow)((Control)e.CommandSource).Parent.Parent;
            var service = ServiceContainer.GetService<IDictionaryManageService>();
            switch (e.CommandName)
            {
                case "MoveUp":
                    if (service.MoveUpEntry(treeTypes.SelectedNode.Value.ToGuid(), row.Attributes["Value"].ToGuid()))
                    {
                        ShowEnties();
                    }
                    break;
                case "MoveDown":
                    if (service.MoveDownEntry(treeTypes.SelectedNode.Value.ToGuid(), row.Attributes["Value"].ToGuid()))
                    {
                        ShowEnties();
                    }
                    break;
            }
        }

        protected void btnDeleteEntry_Click(object sender, EventArgs e)
        {
            var service = ServiceContainer.GetService<IDictionaryManageService>();
            if (service.RemoveEntry(treeTypes.SelectedNode.Value.ToGuid(), fieldValue.Value.ToGuid()))
            {
                ShowEnties();
            }
        }

        protected void btnRefreshEntries_Click(object sender, EventArgs e)
        {
            ShowEnties();
        }

        void BindEntries()
        {
            var service = ServiceContainer.GetService<IDictionaryService>();
            IEnumerable<DictionaryData> entries = treeTypes.SelectedNode == null
                                      ? null
                                      : service.GetDataItems(treeTypes.SelectedNode.Value.ToGuid(),CurrentApplicationContext.CompanyId);
            gridItem.DataSource = entries;
            gridItem.DataBind();
        }

        protected void PageQueryAdapter1_PerformGetPageData(object sender, PerformGetPageDataEventArgs e)
        {
            if (treeTypes.SelectedNode != null)
            {
                var service = ServiceContainer.GetService<IDictionaryService>();
                IEnumerable<DictionaryData> entries = service.GetDataItems(treeTypes.SelectedNode.Value.ToGuid(),CurrentApplicationContext.CompanyId);
                e.DataSource = entries == null ? null : entries.Skip(e.PageSize * e.PageIndex).Take(e.PageSize);
            }
        }

        protected void PageQueryAdapter1_PerformGetRecordCount(object sender, PerformGetRecordCountEventArgs e)
        {
            if (treeTypes.SelectedNode != null)
            {
                var service = ServiceContainer.GetService<IDictionaryService>();
                IEnumerable<DictionaryData> entries =
                    service.GetDataItems(treeTypes.SelectedNode.Value.ToGuid(), CurrentApplicationContext.CompanyId); ;
                e.RecordCount = entries != null ? entries.Count() : 0;
            }
        }

        [WebMethod, ScriptMethod]
        public static Boolean AddDictionaryData(Guid categoryId, string name)
        {
            var service = ServiceContainer.GetService<IDictionaryService>();
            var entries = service.GetDataItems(categoryId);
            if (entries == null)
            {
                return false;
            }
            foreach (var entry in entries)
            {
                if (string.Compare(entry.Name,name,true)==0)
                {
                    return false;
                }
            }
            ServiceContainer.GetService<IDictionaryManageService>().AddEntry(categoryId, name,CurrentApplicationContext.CompanyId);
            return true;
        }

        [WebMethod, ScriptMethod]
        public static Boolean ModifyDictionaryData(Guid categoryId,Guid dataValue,string name)
        {
            var service = ServiceContainer.GetService<IDictionaryService>();
            var entries = service.GetDataItems(categoryId);
            if (entries==null)
            {
                return false;
            }
            foreach (var entry in entries)
            {
                if (entry.Value!=dataValue&& string.Compare(entry.Name, name, true) == 0)
                {
                    return false;
                }
            }
            DictionaryData dictionaryEntry = entries.FirstOrDefault(entry => entry.Value == dataValue);
            dictionaryEntry.Name = name;
            ServiceContainer.GetService<IDictionaryManageService>().ModifyEntry(dictionaryEntry);
            return true;
        }
    }
}
